/* vcc/cmd.c 
 * 
 * This file is part of vcc. 
 * 
 * vcc is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * vcc is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with vcc. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>

#include <vcc/vcc.h>
#include <vcc/version.h>
#include <vcc/pretty.h>
#include <vcc/socket.h>



int do_cmd_help(char *);
int do_cmd_quit(char *);
int do_cmd_ls(char *);
int do_cmd_ls_bh(struct vcc_request *);
int do_cmd_rate(char *);

int read_msg(struct vcc_request *);

extern char usrname[];
extern int rate;

int get_users(void);

struct cmdtable {
	char 		*cmd;
	int 		(* do_cmd) (char *);
	char 		*help;
} cmdtab[] = {
	{ "-help", do_cmd_help, "Show information about every message. " }, 
	{ "-quit", do_cmd_quit, "Disconnect to server and exit vcc. " }, 
	{ "-ls", do_cmd_ls, "List all users online now. " }, 
	{ "-rate", do_cmd_rate, "Change message refresh rate. " }, 
	{ NULL, NULL, NULL }
};

#define clear_line() 	fprintf(stderr, "\033[2K\r")


int do_cmd(char *s) {
	struct cmdtable *t;

	for (t = cmdtab; t->cmd; t++) 
		if (!strncmp(t->cmd, s, strlen(t->cmd))) 
			return t->do_cmd(s);
	
	pretty_unknow_cmd(s);

	return 0;
}


int do_cmd_help(char *s) {
	struct cmdtable *t;

	for (t = cmdtab; t->cmd; t++) 
		pretty_cmd_help(t->cmd, t->help);
	
	return 0;
}


int do_cmd_quit(char *s) {
	printf("bye. \n");
	exit(0);

	return 0;
}


int do_cmd_ls(char *s) {
	get_users();

	return 0;
}


int do_cmd_rate(char *s) {
	int n;

	printf("Current rate: %d Hz\n", rate / 1000);
	fprintf(stderr, "New rate (0 < rate <= 100): ");
	scanf("%d", &n);

	if (n > 100) {
		fprintf(stderr, "*** too fast. \n"
				"0 < rate <= 100\n");

		return 1;
	}

	rate = 1000 / n;
	printf("New rate: %d Hz\n", n);

	return 0;
}


int do_cmd_ls_bh(struct vcc_request *req) {
	int n, i;

	n = ntohl(req->uid);

	clear_line();

	if (unlikely(ntohl(req->reqtype) != REQ_CTL_USRS)) {
		fprintf(stderr, "--- do_cmd_ls_bh: bad package. \n");

		return 1;
	}

	for (i = 0; i < n; i++) 
		printf("%s\n", req->msg + i * USRNAME_SIZE);

	pretty_prompt(usrname);

	return 0;
}


